﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication6.BIZ;
using MvcApplication6.Models;

namespace MvcApplication6.Controllers
{
    public class AdminController : Controller
    {
        //
        // GET: /Admin/
        MenuL1BIZ BIZ_L1 = new MenuL1BIZ();
        MenuL2BIZ BIZ_L2 = new MenuL2BIZ();
        MenuL3BIZ BIZ_L3 = new MenuL3BIZ();
        EventBIZ BIZ_Event = new EventBIZ();
        ProductBIZ BIZ_Product = new ProductBIZ();
        ImageBIZ BIZ_Image = new ImageBIZ();
        Category_eventBIZ BIZ_CategoryEvent = new Category_eventBIZ();
        UserBIZ BIZ_User = new UserBIZ();

        public ActionResult Index()
        {
            return View();
        }

        //1-----------------------------------------------AddMenuL1
        [HttpGet]
        public ActionResult AddMenuL1()
        {
            if (Session["checkLoginAbcuser"] != null)
            {
                return View();
            }
            else
            {
                return RedirectToAction("Error", "Shared");
            }
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult AddMenuL1(MenuL1Model model, string Command)
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            if (Command == "Create")
            {
                List<MenuL1Model> menuL1_lst = BIZ_L1.Menu_l1Select();
                if (menuL1_lst.Count < 7)
                {
                    ViewBag.equal7 = "NOT";
                    // TODO: for button Create
                    int _check = 0;
                    if (ModelState.IsValid)
                    {
                        model.Name = model.Name.Trim();

                        _check = BIZ_L1.Menu_l1Insert(model.Name, model.Position);
                    }
                    if (_check > 0)
                    {
                        ModelState.Clear();
                        model = new MenuL1Model();
                    }
                }
                else
                {
                    ViewBag.equal7 = "OK";
                }
            }

            return View(model);
        }

        //Tao Edit cho Menu 1.
        [HttpGet]
        public ActionResult EditMenuL1()
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            MenuL1Model model = new MenuL1Model();
            string MenuId = Request.QueryString["MenuId"];

            int _chonID = 0;
            if (MenuId != null)
            {
                _chonID = int.Parse(MenuId);
                model = BIZ_L1.Menu_l1SearchById(_chonID);
            }

            return View(model);
        }
        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult EditMenuL1(MenuL1Model model)
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            if (model.Id != 0)
            {
                int _check = 0;
                if (ModelState.IsValid)
                {
                    model.Name = model.Name.Trim();

                    _check = BIZ_L1.Menu_l1Update(model.Id, model.Name, model.Position);
                }
                if (_check > 0)
                {
                    return RedirectToAction("Index", "Home");
                }
            }

            return View(model);
        }

        //Tao Edit cho Menu 2.
        [HttpGet]
        public ActionResult EditMenuL2()
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            MenuL2Model model = new MenuL2Model();
            string MenuId = Request.QueryString["MenuId"];

            int _chonID = 0;
            if (MenuId != null)
            {
                _chonID = int.Parse(MenuId);
                model = BIZ_L2.Menu_l2SearchById(_chonID);

                List<MenuL1Model> lst = new List<MenuL1Model>();
                lst = BIZ_L1.Menu_l1Select();
                ViewBag.Id_l1 = new SelectList(lst, "id", "name", model.Id_l1);
                ViewBag.chonID = model.Id_l1;
            }

            return View(model);
        }
        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult EditMenuL2(MenuL2Model model)
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            if (model.Id != 0)
            {
                int _check = 0;
                if (ModelState.IsValid)
                {
                    model.Name = model.Name.Trim();

                    _check = BIZ_L2.Menu_l2Update(model.Id, model.Id_l1, model.Name, model.Position);
                }
                if (_check > 0)
                {
                    return RedirectToAction("Index", "Home");
                }
            }

            List<MenuL1Model> lst = new List<MenuL1Model>();
            lst = BIZ_L1.Menu_l1Select();
            ViewBag.Id_l1 = new SelectList(lst, "id", "name");
            return View(model);
        }

        //Tao Edit cho Menu 3.
        [HttpGet]
        public ActionResult EditMenuL3()
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            MenuL3Model model = new MenuL3Model();
            string MenuId = Request.QueryString["MenuId"];

            int _chonID = 0;
            if (MenuId != null)
            {
                _chonID = int.Parse(MenuId);
                model = BIZ_L3.Menu_l3SearchById(_chonID);

                List<MenuL2Model> lst = new List<MenuL2Model>();
                lst = BIZ_L2.Menu_l2Select();
                ViewBag.Id_l2 = new SelectList(lst, "id", "name", model.Id_l2);
                ViewBag.chonID = model.Id_l2;
            }

            return View(model);
        }
        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult EditMenuL3(MenuL3Model model)
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            if (model.Id != 0)
            {
                int _check = 0;
                if (ModelState.IsValid)
                {
                    model.Name = model.Name.Trim();

                    _check = BIZ_L3.Menu_l3Update(model.Id, model.Id_l2, model.Name, model.Position);
                }
                if (_check > 0)
                {
                    return RedirectToAction("Index", "Home");
                }
            }

            List<MenuL2Model> lst = new List<MenuL2Model>();
            lst = BIZ_L2.Menu_l2Select();
            ViewBag.Id_l2 = new SelectList(lst, "id", "name");
            return View(model);
        }

        //2-----------------------------------------------AddMenuL2
        [HttpGet]
        public ActionResult AddMenuL2()
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            string Id_l1 = Request.QueryString["Id_l1"];
            string menu1Name = Request.QueryString["menu1Name"];

            int _chonID = 0;
            if (Id_l1 != null && menu1Name != null)
            {
                _chonID = int.Parse(Id_l1);
            }

            List<MenuL1Model> lst = new List<MenuL1Model>();
            lst = BIZ_L1.Menu_l1Select();
            ViewBag.Id_l1 = new SelectList(lst, "id", "name", _chonID);
            ViewBag.chonID = _chonID;

            return View();
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult AddMenuL2(MenuL2Model model, string Command)
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            if (Command == "Create")
            {
                // TODO: for button Create
                int _check = 0;
                if (ModelState.IsValid)
                {
                    model.Name = model.Name.Trim();

                    _check = BIZ_L2.Menu_l2Insert(model.Id_l1, model.Name, model.Position);
                }
                if (_check > 0)
                {
                    ModelState.Clear();
                    model = new MenuL2Model();
                }
            }

            List<MenuL1Model> lst = new List<MenuL1Model>();
            lst = BIZ_L1.Menu_l1Select();
            ViewBag.Id_l1 = new SelectList(lst, "id", "name");

            return View(model);
        }

        //3-----------------------------------------------AddMenuL3
        [HttpGet]
        public ActionResult AddMenuL3()
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            string Id_l2 = Request.QueryString["Id_l2"];
            string menu2Name = Request.QueryString["menu2Name"];

            int _chonID = 0;
            if (Id_l2 != null && menu2Name != null)
            {
                _chonID = int.Parse(Id_l2);
            }

            List<MenuL2Model> lst = new List<MenuL2Model>();
            lst = BIZ_L2.Menu_l2Select();
            ViewBag.Id_l2 = new SelectList(lst, "id", "name", _chonID);
            ViewBag.chonID = _chonID;

            return View();
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult AddMenuL3(MenuL3Model model, string Command)
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            if (Command == "Create")
            {
                // TODO: for button Create
                int _check = 0;
                if (ModelState.IsValid)
                {
                    model.Name = model.Name.Trim();

                    _check = BIZ_L3.Menu_l3Insert(model.Id_l2, model.Name, model.Position);
                }
                if (_check > 0)
                {
                    ModelState.Clear();
                }
            }

            List<MenuL2Model> lst = new List<MenuL2Model>();
            lst = BIZ_L2.Menu_l2Select();
            ViewBag.Id_l2 = new SelectList(lst, "id", "name");

            return View(model);
        }

        //4-----------------------------------------------AddNews
        [HttpGet]
        public ActionResult AddNews()
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            EventModel model = new EventModel();

            //Lay pagramID
            string _proID = Request.QueryString["EventId"];

            int _chonID = 0;
            if (_proID != null)
            {
                _chonID = int.Parse(_proID);
            }
            if (_chonID != 0)
            {
                model = BIZ_Event.EventSearchById(_chonID);

                //Dropdown list Category event
                List<Category_eventModel> IdCe_1 = new List<Category_eventModel>();
                IdCe_1 = BIZ_CategoryEvent.Category_eventSearch();
                ViewBag.IdCe = new SelectList(IdCe_1, "id", "name", model.IdCe);

                ViewBag.Button = "Edit";

                return View(model);
            }

            //Set gia tri mac dinh cho ngay thang nam khi khong phai la khuyen mai
            model.StartDate = DateTime.Now.ToString("MM/dd/yyyy");
            model.EndDate = DateTime.Now.ToString("MM/dd/yyyy");

            //Dropdown list Category event
            List<Category_eventModel> IdCe = new List<Category_eventModel>();
            IdCe = BIZ_CategoryEvent.Category_eventSearch();

            ViewBag.IdCe = new SelectList(IdCe, "id", "name");

            return View(model);
        }

        [HttpPost, ValidateInput(false), ValidateAntiForgeryToken]
        public ActionResult AddNews(EventModel model, string Command)
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            int _check = 0;
            if (Command == "Create")
            {
                // TODO: for button Create
                if (ModelState.IsValid)
                {
                    model.Title = model.Title.Trim();

                    if (model.Image == null)
                    {
                        model.Image = "";
                    }
                    if (model.Content == null)
                    {
                        model.Content = "";
                    }

                    //Upload File len
                    if (model.FileImage != null)
                    {
                        if (model.FileImage.FileName.Length > 20)
                        {
                            //
                            //model.Image = "";
                        }
                        else
                        {
                            string name = "";
                            string[] parts = model.FileImage.FileName.Split('.');

                            name = parts[0];// +DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute;
                            name = name + "." + parts[parts.Length - 1];

                            string savedFileName = Path.Combine(Server.MapPath("~/Upload/Images"), Path.GetFileName(name));
                            model.FileImage.SaveAs(savedFileName); //Up len server

                            model.Image = name;
                            //int i = BIZ_Image.ImageInsert(name);
                        }
                    }

                    _check = BIZ_Event.EventInsert(model.IdCe, model.Title, model.Title2, model.Image, model.StartDate, model.EndDate, model.Content);

                    if (_check > 0)
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
            }
            else
            {
                if (Command == "Edit")
                {
                    model.Title = model.Title.Trim();

                    if (model.Image == null)
                    {
                        model.Image = "";
                    }
                    if (model.Content == null)
                    {
                        model.Content = "";
                    }

                    //Upload File len
                    if (model.FileImage != null)
                    {
                        if (model.FileImage.FileName.Length > 20)
                        {
                            //
                            //model.Image = "";
                        }
                        else
                        {
                            string name = "";
                            string[] parts = model.FileImage.FileName.Split('.');

                            name = parts[0];// +DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute;
                            name = name + "." + parts[parts.Length - 1];

                            string savedFileName = Path.Combine(Server.MapPath("~/Upload/Images"), Path.GetFileName(name));
                            model.FileImage.SaveAs(savedFileName); //Up len server

                            model.Image = name;
                            //int i = BIZ_Image.ImageInsert(name);
                        }
                    }

                    //Update product
                    _check = BIZ_Event.EventUpdate(model.Id, model.IdCe, model.Title, model.Title2, model.Image, model.StartDate, model.EndDate, model.Content);
                    if (_check > 0)
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
            }

            if (_check > 0)
            {
                ViewBag.error = "OK";
                EventModel model_2 = new EventModel();
                model = model_2;
                ModelState.Clear();
            }
            else
            {
                ViewBag.error = "NOT";
            }

            //Dropdown list Category event
            List<Category_eventModel> IdCe = new List<Category_eventModel>();
            IdCe = BIZ_CategoryEvent.Category_eventSearch();

            ViewBag.IdCe = new SelectList(IdCe, "id", "name");

            return View(model);
        }

        //------------------------------------------------AddNews_2 voi paragram CategoryEventId
        [HttpGet]
        public ActionResult AddNews_2()
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            EventModel model = new EventModel();

            //Lay pagramID
            string _proID = Request.QueryString["CategoryEventId"];

            int _chonID = 0;
            if (_proID != null)
            {
                _chonID = int.Parse(_proID);
            }
            if (_chonID != 0)
            {
                //Dropdown list Category event
                Category_eventModel categoryModel = new Category_eventModel();
                categoryModel = BIZ_CategoryEvent.Category_eventSearchById(_chonID);
                ViewBag.nameCategory = categoryModel.Name;

                //Set gia tri mac dinh cho ngay thang nam khi khong phai la khuyen mai
                model.StartDate = DateTime.Now.ToString("MM/dd/yyyy");
                model.EndDate = DateTime.Now.ToString("MM/dd/yyyy");

                model.IdCe = categoryModel.Id;
                return View(model);
            }

            return View(model);
        }

        //5--------------------------------------------------AddProduct
        /// <summary>
        /// Filter classes based on student id
        /// </summary>
        /// <param name="studentid"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult LoadClassesByMenuL1Id(string menuL1id)
        {
            int idL1 = Convert.ToInt32(menuL1id);

            var MenuL2 = BIZ_L2.Menu_l2SearchById_l1(idL1);

            var data = MenuL2.Select(m => new SelectListItem()
            {
                Text = m.Name,
                Value = m.Id.ToString(),

            });

            return Json(data, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// filter marks based on class id
        /// </summary>
        /// <param name="classid"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult LoadMarksByMenuL2Id(string menuL2id)
        {
            int idL2 = Convert.ToInt32(menuL2id);

            var MenuL3 = BIZ_L3.Menu_l3SearchById_l2(idL2);

            var data = MenuL3.Select(m => new SelectListItem()
            {
                Text = m.Name,
                Value = m.Id.ToString(),

            });
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult AddProduct()
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            AddProductModel product = new AddProductModel();
            ProductModel model = new ProductModel();

            //Lay pagramID
            string _proID = Request.QueryString["ProductId"];

            int _chonID = 0;
            if (_proID != null)
            {
                _chonID = int.Parse(_proID);
            }
            if (_chonID != 0)
            {
                model = BIZ_Product.ProductSearchById(_chonID);

                //Menu 1
                MenuL1Model l1 = new MenuL1Model();
                l1.Id = 0;
                l1.Name = "Select a menu 1";
                List<MenuL1Model> lst_l1 = new List<MenuL1Model>();
                lst_l1 = BIZ_L1.Menu_l1Select();
                lst_l1.Insert(0, l1);

                product.MenuL1 = lst_l1;
                //Memu 2
                MenuL2Model l2 = new MenuL2Model();
                l2.Id = 0;
                l2.Name = "Select a menu 2";
                List<MenuL2Model> lst_l2 = new List<MenuL2Model>();
                lst_l2 = BIZ_L2.Menu_l2SearchById_l1(model.IdL1);
                lst_l2.Insert(0, l2);

                product.MenuL2 = lst_l2;

                if (model.IdL2 == 6)
                {
                    //Menu 3
                    MenuL3Model l3 = new MenuL3Model();
                    l3.Id = 0;
                    l3.Name = "Select a menu 3";
                    List<MenuL3Model> lst_3_0 = new List<MenuL3Model>();
                    lst_3_0.Add(l3);

                    product.MenuL3 = lst_3_0;
                }
                else
                {
                    //Menu 3
                    MenuL3Model l3 = new MenuL3Model();
                    l3.Id = 0;
                    l3.Name = "Select a menu 3";
                    List<MenuL3Model> lst_l3 = new List<MenuL3Model>();
                    lst_l3 = BIZ_L3.Menu_l3SearchById_l2(model.IdL2);
                    lst_l3.Insert(0, l3);

                    product.MenuL3 = lst_l3;
                }

                    //Thay doi lai true, false cho checkbox
                    if (model.ProsalesFlag == 1)
                    {
                        model.checkbox_ProsalesFlag = true;
                    }
                    else
                    {
                        model.checkbox_ProsalesFlag = false;
                    }
                    //Modifi NewproFlag tu true thanh 1. false thanh 0
                    if (model.NewproFlag == 1)
                    {
                        model.checkbox_NewproFlag = true;                        
                    }
                    else
                    {
                        model.checkbox_NewproFlag = false;   
                    }
                    //Modifi ProsaleFlag tu true thanh 1. false thanh 0
                    if (model.ProsaleFlag == 1)
                    {
                        model.checkbox_ProsaleFlag = true;                        
                    }
                    else
                    {
                        model.checkbox_ProsaleFlag = false;   
                    }

                    //Thay doi lai idmenu2, idmenu3 khi no bang 6
                    if (model.IdL2 == 6)
                    {
                        model.IdL2 = 0;
                        model.IdL3 = 0;
                    }
                    else
                    {
                        if (model.IdL3 == 6)
                        {
                            model.IdL3 = 0;
                        }
                    }

                product.modelController = model;

                ViewBag.Button = "Edit";
                return View(product);
            }

            List<MenuL1Model> lst_1 = new List<MenuL1Model>();
            lst_1 = BIZ_L1.Menu_l1Select();
            MenuL1Model l1_new = new MenuL1Model();
            l1_new.Id = 0;
            l1_new.Name = "Select a menu 1";
            lst_1.Insert(0, l1_new);

            //Memu 2
            MenuL2Model l2_new = new MenuL2Model();
            l2_new.Id = 0;
            l2_new.Name = "Select a menu 2";
            List<MenuL2Model> lst_2 = new List<MenuL2Model>();
            lst_2.Add(l2_new);

            //Menu 3
            MenuL3Model l3_new = new MenuL3Model();
            l3_new.Id = 0;
            l3_new.Name = "Select a menu 3";
            List<MenuL3Model> lst_3 = new List<MenuL3Model>();
            lst_3.Add(l3_new);

            product.MenuL1 = lst_1;
            product.MenuL2 = lst_2;
            product.MenuL3 = lst_3;

            product.modelController = new ProductModel();

            return View(product);
        }

        [HttpPost, ValidateInput(false), ValidateAntiForgeryToken]
        public ActionResult AddProduct(AddProductModel product, string Command)
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            

            ProductModel model = product.modelController;

            //event change choose Droplist
            int _check = 0;
            if (Command == "Create")
            {
                // TODO: for button Create
                //int _check = 0;
                if (ModelState.IsValid)
                {
                    string name = "";
                    model.IntPro = ""; //Gia tri khong can den nua nen.

                    model.Name = model.Name.Trim();

                    //Gia tri cua menu2 va menu3 khi bang 0
                    if (model.IdL2 == 0)
                    {
                        model.IdL2 = 6;
                        model.IdL3 = 6;
                    }
                    else
                    {
                        if (model.IdL3 == 0)
                        {
                            model.IdL3 = 6;
                        }
                    }

                    //Gia tri introduce_pro
                    if (model.introduce_pro == null)
                    {
                        model.introduce_pro = "";
                    }
                    //Gia tri inf;
                    if (model.InfPro == null)
                    {
                        model.InfPro = "";
                    }
                        //Modifi prosalesFlag tu true thanh 1. false thanh 0
                        if (model.checkbox_ProsalesFlag)
                        {
                            model.ProsalesFlag = 1;
                        }
                        else
                        {
                            model.ProsalesFlag = 0;
                        }
                        //Modifi NewproFlag tu true thanh 1. false thanh 0
                        if (model.checkbox_NewproFlag)
                        {
                            model.NewproFlag = 1;
                        }
                        else
                        {
                            model.NewproFlag = 0;
                        }
                        //Modifi ProsaleFlag tu true thanh 1. false thanh 0
                        if (model.checkbox_ProsaleFlag)
                        {
                            model.ProsaleFlag = 1;
                        }
                        else
                        {
                            model.ProsaleFlag = 0;
                        }

                    if (model.Image == null)
                    {
                        model.Image = "";
                    }

                    //Upload File len
                    if (model.FileImage != null)
                    {
                        if (model.FileImage.FileName.Length > 20)
                        {
                            //
                            //model.Image = "";
                        }
                        else
                        {
                            string[] parts = model.FileImage.FileName.Split('.');

                            name = parts[0]; // +DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute;
                            name = name + "." + parts[parts.Length - 1];

                            string savedFileName = Path.Combine(Server.MapPath("~/Upload/Images"), Path.GetFileName(name));
                            model.FileImage.SaveAs(savedFileName); //Up len server

                            model.Image = name;
                            //int i = BIZ_Image.ImageInsert(name);
                        }
                    }

                    if (model.CallToSale == null || "".Equals(model.CallToSale.Trim()))
                    {
                        model.CallToSale = "";
                    }

                    _check = BIZ_Product.ProductInsert(model.IdL1, model.IdL2, model.IdL3, model.Image, model.Position1, model.Position2, model.Position3, model.Position4, model.Position5, model.Position6,
                                                        model.NewproFlag, model.ProsalesFlag, model.ProsaleFlag, 
                                                        model.Name, model.title, model.Warranty, model.MakeIn, model.Price, model.Sale, model.introduce_pro, model.InfPro, model.IntPro, model.CallToSale);
                    
                    if (_check > 0)
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
            }
            else
            {
                if (Command == "Edit")
                {
                    //Upload File len
                    if (model.FileImage != null)
                    {
                        if (model.FileImage.FileName.Length > 20)
                        {
                            //
                            //model.Image = "";
                        }
                        else
                        {
                            string name = "";
                            string[] parts = model.FileImage.FileName.Split('.');

                            name = parts[0];// +DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute;
                            name = name + "." + parts[parts.Length - 1];

                            string savedFileName = Path.Combine(Server.MapPath("~/Upload/Images"), Path.GetFileName(name));
                            model.FileImage.SaveAs(savedFileName); //Up len server

                            model.Image = name;
                            //int i = BIZ_Image.ImageInsert(name);
                        }
                    }

                    //Update product
                    model.IntPro = ""; //Gia tri khong can den nua nen.

                    model.Name = model.Name.Trim(); // chinh lai xoa khoang trang dau va cuoi

                    //Gia tri cua menu2 va menu3 khi bang 0
                    if (model.IdL2 == 0)
                    {
                        model.IdL2 = 6;
                        model.IdL3 = 6;
                    }
                    else
                    {
                        if (model.IdL3 == 0)
                        {
                            model.IdL3 = 6;
                        }
                    }

                    //Gia tri introduce_pro
                    if (model.introduce_pro == null)
                    {
                        model.introduce_pro = "";
                    }
                    //Gia tri inf;
                    if (model.InfPro == null)
                    {
                        model.InfPro = "";
                    }

                        //Modifi ProsalesFlag tu true thanh 1. false thanh 0
                        if (model.checkbox_ProsalesFlag)
                        {
                            model.ProsalesFlag = 1;
                        }
                        else
                        {
                            model.ProsalesFlag = 0;
                        }
                        //Modifi NewproFlag tu true thanh 1. false thanh 0
                        if (model.checkbox_NewproFlag)
                        {
                            model.NewproFlag = 1;
                        }
                        else
                        {
                            model.NewproFlag = 0;
                        }
                        //Modifi ProsaleFlag tu true thanh 1. false thanh 0
                        if (model.checkbox_ProsaleFlag)
                        {
                            model.ProsaleFlag = 1;
                        }
                        else
                        {
                            model.ProsaleFlag = 0;
                        }

                    if (model.Image == null)
                    {
                        model.Image = "";
                    }

                    if (model.CallToSale == null || "".Equals(model.CallToSale.Trim()))
                    {
                        model.CallToSale = "";
                    }

                    _check = BIZ_Product.ProductUpdate(model.Id, model.IdL1, model.IdL2, model.IdL3, model.Image, model.Position1, model.Position2, model.Position3, model.Position4, model.Position5, model.Position6,
                                                    model.NewproFlag, model.ProsalesFlag, model.ProsaleFlag, 
                                                    model.Name, model.title, model.Warranty, model.MakeIn, model.Price, model.Sale, model.introduce_pro, model.InfPro, model.IntPro,  model.CallToSale);
                    if (_check > 0)
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
            }

            //-------------------------------------------------------------
            if (_check > 0)
            {
                ViewBag.error = "OK";
                product.modelController = new ProductModel(); ;
                ModelState.Clear();
            }
            else
            {
                ViewBag.error = "NOT";
            }

            //Tra ve gia tri cho droplist
            List<MenuL1Model> lst_1 = new List<MenuL1Model>();
            lst_1 = BIZ_L1.Menu_l1Select();
            MenuL1Model l1_new = new MenuL1Model();
            l1_new.Id = 0;
            l1_new.Name = "Select a menu 1";
            lst_1.Insert(0, l1_new);

            //Memu 2
            MenuL2Model l2_new = new MenuL2Model();
            l2_new.Id = 0;
            l2_new.Name = "Select a menu 2";
            List<MenuL2Model> lst_2 = new List<MenuL2Model>();
            lst_2.Add(l2_new);

            //Menu 3
            MenuL3Model l3_new = new MenuL3Model();
            l3_new.Id = 0;
            l3_new.Name = "Select a menu 3";
            List<MenuL3Model> lst_3 = new List<MenuL3Model>();
            lst_3.Add(l3_new);

            product.MenuL1 = lst_1;
            product.MenuL2 = lst_2;
            product.MenuL3 = lst_3;
            //------------------------------------------

            product._check_ket_qua = _check;
            return View(product);
        }

        //AddProduct truong hop 2 với param
        [HttpGet]
        public ActionResult AddProduct_2()
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            AddProductModel product = new AddProductModel();
            ProductModel model = new ProductModel();

            //admin/addproduct_2?MenuId1=id1&MenuName1=Name1&MenuId2=Id2&MenuName2=Name2&MenuId3=Id3&MenuName3=Name3
            //Lay pagram
            string MenuId1 = Request.QueryString["MenuId1"];
            string MenuName1;

            string MenuId2 = Request.QueryString["MenuId2"];
            string MenuName2;

            string MenuId3 = Request.QueryString["MenuId3"];
            string MenuName3;

            int id1, id2, id3;
            id1 = 0; id2 = 0; id3 = 0;

            if (MenuId1 != null)
            {
                id1 = int.Parse(MenuId1);

                MenuName1 = BIZ_L1.Menu_l1SearchById(id1).Name;
                ViewBag.MenuName1 = MenuName1;

                model.IdL1 = id1;
            }
            if (MenuId2 != null)
            {
                id2 = int.Parse(MenuId2);
            }
            if (MenuId3 != null)
            {
                id3 = int.Parse(MenuId3);
            }

            //Kiem tra
            //id3
            if (id3 == 0)
            {
                ViewBag.MenuName3 = "Không có menu 3";
            }
            else
            {
                MenuName3 = BIZ_L3.Menu_l3SearchById(id3).Name;
                ViewBag.MenuName3 = MenuName3;
            }
            //id2
            if (id2 == 0)
            {
                ViewBag.MenuName2 = "Không có menu 2";
                ViewBag.MenuName3 = "Không có menu 3";
            }
            else
            {
                MenuName2 = BIZ_L2.Menu_l2SearchById(id2).Name;
                ViewBag.MenuName2 = MenuName2;
            }

            model.IdL2 = id2;
            model.IdL3 = id3;
            product.modelController = model;

            return View(product);
        }

        //26/03------------------------Upload Image--------------------------
        public ActionResult UploadFile()
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            ImageModel model = new ImageModel();

            return View(model);
        }

        [HttpPost]
        public ActionResult UploadFile(ImageModel model)
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            List<string> lst = new List<string>();

            foreach (var p in model.Files)
            {
                if (p.FileName.Length > 20 || !isValidImage(p.FileName))
                {
                    //
                }
                else
                {
                    if (p.ContentLength == 0)
                        continue;

                    string[] parts = p.FileName.Split('.');

                    //string name = parts[0] + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute;
                    string name = parts[0];
                    name = name + "." + parts[parts.Length - 1];

                    string savedFileName = Path.Combine(Server.MapPath("~/Upload/Images"), Path.GetFileName(name));
                    p.SaveAs(savedFileName);

                    int i = BIZ_Image.ImageInsert(name);
                    lst.Add(name);
                }
            }
            model.listNameFile = lst;

            return View(model);
        }

        string getExtension(string filename) {
            var parts = filename.Split('.');
            return parts[parts.Length - 1];
        }
        //Helper function to determine if the file type is valid
        bool isValidImage(string filename) {
            var ext = getExtension(filename);
            switch (ext.ToLower()) {
                case "jpg":
                case "jpeg":
                case "gif":
                case "bmp":
                case "png":
                    //It is an image - allow it
                    return true;
            }
            //It wasn't a valid extension - don't submit the form
            return false;
        }
        //---- end upload image

        //Login: Dang Nhap
        public ActionResult Login(UserModel model)
        {
            if (model.name != null && model.password != null)
            {
                List<UserModel> lst = BIZ_User.UserSearchByUser(model.name, model.password);
                if (lst.Count != 0)
                {
                    model = lst[0];
                    Session["checkLoginAbcuser"] = 11;
                    return RedirectToAction("Index", "Home");
                }
                ViewBag.success = "NOT";
            }

            return View(model);
        }

        // GET: ChangePassword
        public ActionResult ChangePassword()
        {
            return View();
        }
        // POST: ChangePassword
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                List<UserModel> lst = BIZ_User.UserSearchByUser(model.Name, model.OldPassword);
                ChangePasswordModel changePass = new ChangePasswordModel();
                int _check = 0;
                if (lst.Count != 0)
                {
                    UserModel user = lst[0];
                    changePass.Name = user.name;
                    changePass.OldPassword = user.password;
                    int id = user.UserId;

                    _check = BIZ_User.UserUpdate(id, model.Name, model.NewPassword);

                    return View("Login");
                }

                ViewBag.success = "NOT";
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        [HttpGet]
        public ActionResult CategoryEvent()
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            Category_eventModel model = new Category_eventModel();

            //Lay pagramID
            string _proID = Request.QueryString["Category_eventId"];

            int _chonID = 0;
            if (_proID != null)
            {
                _chonID = int.Parse(_proID);
            }
            if (_chonID != 0)
            {
                model = BIZ_CategoryEvent.Category_eventSearchById(_chonID);
                
                ViewBag.Button = "Edit";
                //show Category event
                return View(model);
            }

            return View(model);
        }

        [HttpPost, ValidateInput(false), ValidateAntiForgeryToken]
        public ActionResult CategoryEvent(Category_eventModel model, string Command)
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            int _check = 0;
            if (Command == "Create")
            {
                // TODO: for button Create
                if (ModelState.IsValid)
                {
                    model.Name = model.Name.Trim();
                    //Instert
                    _check = BIZ_CategoryEvent.Category_eventInsert(model.Name, model.Content_template);
                }
            }
            else
            {
                if (Command == "Edit")
                {
                    model.Name = model.Name.Trim();
                    //Update
                    _check = BIZ_CategoryEvent.Category_eventUpdate(model.Id, model.Name, model.Content_template);
                    if (_check > 0)
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
            }

            if (_check > 0)
            {
                ViewBag.error = "OK";
                Category_eventModel model_2 = new Category_eventModel();
                model = model_2;
                ModelState.Clear();
            }
            else
            {
                ViewBag.error = "NOT";
            }

            return View(model);
        }

        //------------------------------Update Sale---------------------------------------
        //---http://localhost:54094/Admin/SaleAll?IdSale=45&MenuLv=2&NameMenu=test-------
        [HttpGet]
        public ActionResult SaleAll()
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            UpdateSaleModel model = new UpdateSaleModel();

            //Lay pagramID
            string _sale = Request.QueryString["IdSale"];
            string _menu = Request.QueryString["MenuLv"];
            string _nameMenu = Request.QueryString["NameMenu"];

            int _idSale = 0;
            int _menuLv = 0;
            if (_sale != null && _menu != null)
            {
                _idSale = int.Parse(_sale);
                _menuLv = int.Parse(_menu);

                model.NameMenu = _nameMenu;
                model.IdSale = _idSale;
                model.MenuLv = _menuLv;

                return View(model);
            }

            return View(model);
        }

        [HttpPost, ValidateInput(false), ValidateAntiForgeryToken]
        public ActionResult SaleAll(UpdateSaleModel model)
        {
            if (Session["checkLoginAbcuser"] == null)
            {
                return RedirectToAction("Error", "Shared");
            }

            int _check = 0;
            //Thuc hien update sale
            //cò 3 truong hop
            //[10:29:21 PM] ta chi thanh: 1: if (MenuLv = 1) {}
            //[10:31:25 PM] ta chi thanh: ----> update sale = 30 from product where id_l1=IdSale
            //[10:31:44 PM] ta chi thanh: 2: if (MenuLv = 2) {}
            //[10:32:01 PM] ta chi thanh: ----> update sale = 30 from product where id_l2=IdSale
            //[10:32:12 PM] ta chi thanh: 3: if (MenuLv = 3) {}
            //[10:32:27 PM] ta chi thanh: ---> update sale = 30 from product where id_l3=IdSale
            if (model.MenuLv == 1)
            {
                _check = BIZ_Product.ProductUpdateSaleByID_L1(model.IdSale, model.Sale);
            }
            else
            {
                if (model.MenuLv == 2)
                {
                    _check = BIZ_Product.ProductUpdateSaleByID_L2(model.IdSale, model.Sale);
                }
                else
                {
                    if (model.MenuLv == 3)
                    {
                        _check = BIZ_Product.ProductUpdateSaleByID_L3(model.IdSale, model.Sale);
                    }
                }
            }

            if (_check > 0)
            {
                return RedirectToAction("Index", "Home");
            }

            return View(model);
        }

        [HttpPost]
        public void UploadImage2()
        {
            for (int i = 0; i < Request.Files.Count; i++)
            {
                var file = Request.Files[i];

                var fileName = Path.GetFileName(file.FileName);

                var path = Path.Combine(Server.MapPath("~/Upload/Images"), fileName);
                file.SaveAs(path);

                BIZ_Image.ImageInsert(fileName);
            }
        }
		
		//Tuyen add- 18082014
        //[HttpPost]
        //[ValidateInput(false)]
        //public ActionResult Create(Post post)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        db.Posts.AddObject(post);
        //        db.SaveChanges();
        //        return RedirectToAction("Index"); 
        //    }
        //    return View(post);
        //}
    }
}
